package com.skynet.amqp.perfect;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@AutoConfigureAfter(RabbitAutoConfiguration.class)
@ConditionalOnProperty(prefix = "amqp-prefect", value = "enabled", havingValue = "true")
@EnableConfigurationProperties(RetryCacheProperties.class)
@SuppressWarnings("ALL")
public class PerfectRabbitAutoConfiguration {

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public MessageSender messageSender() {
        return new MessageSenderImpl();
    }

    @Bean
    public RetryCache retryCache() {
        return new RetryCache();
    }

    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback(RabbitTemplate rabbitTemplate) {
        PerfectRabbitConfirmCallback confirmCallback = new PerfectRabbitConfirmCallback();
        rabbitTemplate.setConfirmCallback(confirmCallback);
        return confirmCallback;
    }

    @Bean
    public RabbitTemplate.ReturnCallback returnCallback(RabbitTemplate rabbitTemplate) {
        PerfectRabbitReturnCallback returnCallback = new PerfectRabbitReturnCallback();
        rabbitTemplate.setReturnCallback(returnCallback);
        return returnCallback;
    }

    @Bean
    public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) {
        // 开启发布确认回调
        connectionFactory.setPublisherConfirms(true);
        connectionFactory.setPublisherReturns(true);
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setMessageConverter(messageConverter());
        return rabbitTemplate;
    }


}
